<?php

namespace app\admin\controller;

use app\common\controller\CommonController;
use app\common\service\AuthService;
use app\common\tools\Data;
use think\Db;

/**
 * 系统权限管理
 * Class Auth
 * @package app\admin\controller
 */
class Auth extends CommonController
{
    /**
     * 默认数据模型
     * @var string
     */
    public $table = 'SystemAuth';

    /**
     * 系统权限管理
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function index()
    {
        $this->title = '系统权限管理';
        $list = Db::name('SystemAuth')->order('id desc')->paginate(10);

        $page = $list->render();
        $this->assign('list',$list);
        $this->assign('page', $page);
        $this->assign('title',$this->title);
        return $this->fetch();
    }

    /**
     * 权限配置节点
     * @return mixed
     * @throws \ReflectionException
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function apply()
    {
        $this->title = '权限配置节点';

        $auth = $this->request->post('id', '0');
        switch (strtolower($this->request->post('action'))) {
            case 'get': // 获取权限配置
                $nodes = AuthService::get();
                $checked = Db::name('SystemAuthNode')->where(['auth' => $auth])->column('node');
                foreach ($nodes as &$node) $node['checked'] = in_array($node['node'], $checked);
                $data = $this->_apply_filter(Data::arr2tree($nodes, 'node', 'pnode', '_sub_'));
                return $this->_success('获取权限节点成功！', $data);
            case 'save': // 保存权限配置
                list($post, $data) = [$this->request->post(), []];
                foreach (isset($post['nodes']) ? $post['nodes'] : [] as $node) {
                    $data[] = ['auth' => $auth, 'node' => $node];
                }
                Db::name('SystemAuthNode')->where(['auth' => $auth])->delete();
                Db::name('SystemAuthNode')->insertAll($data);
                return $this->success('权限授权更新成功！');
            default:
                $id = input('get.id');
                $find = Db::name($this->table)->where(['id'=>$id])->find();
                $this->assign('vo',$find);
                $this->assign('title',$this->title);
                return $this->fetch('apply');
        }

    }

    /**
     * 节点数据拼装
     * @param array $nodes
     * @param integer $level
     * @return array
     */
    private function _apply_filter($nodes, $level = 1)
    {
        foreach ($nodes as $key => $node) if (!empty($node['_sub_']) && is_array($node['_sub_'])) {
            $node[$key]['_sub_'] = $this->_apply_filter($node['_sub_'], $level + 1);
        }
        return $nodes;
    }

    /**
     * 添加系统权限
     * @return array|string
     */
    public function add()
    {
        if($this->request->isPost()){
            $inserData['title'] = input('post.title');
            $inserData['desc'] = input('post.desc');
            $res = Db::name($this->table)->insert($inserData);
            if($res){
                $this->_success('添加权限成功');
            }else{
                $this->_error('添加权限失败');
            }
        }

        return $this->fetch('form');
    }

    /**
     * 编辑系统权限
     * @return array|string
     */
    public function edit()
    {
        if($this->request->isPost()){
            $post_id = input('post.id');
            $updateData['title'] = input('post.title');
            $updateData['desc'] = input('post.desc');
            $res = Db::name($this->table)->where(['id'=>$post_id])->update($updateData);
            if($res){
                $this->_success('编辑系统权限成功');
            }else{
                $this->_error('编辑系统权限失败');
            }

        }
        $id = input('get.id');
        $find = Db::name($this->table)->where(['id'=>$id])->find();
        $this->assign('vo',$find);
        return $this->fetch('form');
    }

    /**
     * 禁用系统权限
     */
    public function forbid()
    {
        $id = input('post.id');
        $updateData['status'] = 0;
        $res = Db::name($this->table)->where(['id'=>$id])->update($updateData);
        if($res){
            $this->_success('禁用系统权限成功');
        }else{
            $this->_error('禁用系统权限失败');
        }

    }

    /**
     * 启用系统权限
     */
    public function resume()
    {
        $id = input('post.id');
        $updateData['status'] = 1;
        $res = Db::name($this->table)->where(['id'=>$id])->update($updateData);
        if($res){
            $this->_success('启用系统权限成功');
        }else{
            $this->_error('启用系统权限失败');
        }
    }

    /**
     * 删除系统权限
     */
    public function remove()
    {
        $id = input('post.id');
        $res = Db::name($this->table)->delete($id);
        if($res){
            $this->_remove_delete_result($res);
            $this->_success('删除系统权限成功');
        }else{
            $this->_error('删除系统权限失败');
        }
    }

    /**
     * 删除结果处理
     * @param boolean $result
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    protected function _remove_delete_result($result)
    {
        if ($result) {
            $where = ['auth' => $this->request->post('id')];
            Db::name('SystemAuthNode')->where($where)->delete();
            return true;
        } else {
            return false;
        }
    }


}